package controllers;

import com.shove.Convert;
import models.files;
import net.sf.json.JSONObject;
import play.Logger;
import play.Play;
import play.db.jpa.Blob;
import utils.ErrorInfo;
import utils.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.Map;

public class FileController  extends BaseController{
    /**
     * 图片查看
     * @param uuid
     * @throws FileNotFoundException
     */
    public static void images(String uuid) throws FileNotFoundException{
        Blob blob = new Blob();
        InputStream is = null;
        try {
            is = new FileInputStream(new File(blob.getStore(), uuid.split("\\.")[0]));
        } catch (Exception e) {
            is = new FileInputStream(Play.getFile("public/images/favicon.png"));
        }
        renderBinary(is);
    }
    /**
     * 上传图片
     * @param imgFile
     */
    public static void uploadImage(File imgFile) {
        Logger.info("uploadImage");
        ErrorInfo error = new ErrorInfo();
        Map<String, Object> fileInfo = FileUtil.uploadFile(imgFile,error);
        if (error.code < 0) {
            JSONObject json = new JSONObject();
            json.put("error", error);
            renderText(json.toString());
        }
        files file=new files();
        file.create_date=new Date();
        file.file_realname = fileInfo.get("file_realname").toString();
        file.filetype = fileInfo.get("filetype").toString();
        file.filename =fileInfo.get("filename").toString();
        file.size = Convert.strToDouble(fileInfo.get("size").toString(),0);
        file.save();
        renderJSON(fileInfo);
    }
    public static void getImg(String filename){

    }
}
